# ------------------------------------------
# 准备工作
# ------------------------------------------

setwd("/Users/eimei/Documents/Rdata/")  # 设定工作空间
data <- read.csv("HRdata.csv")  # 读取数据

newdata <- data[c("EmployeeNumber", "Age", "Department",
                  "EnvironmentSatisfaction", "JobSatisfaction",
                  "MonthlyIncome", "RelationshipSatisfaction")]

# ------------------------------------------
# 任务一
# ------------------------------------------

newdata$TotalSatisfaction <- newdata$EnvironmentSatisfaction + newdata$JobSatisfaction + newdata$RelationshipSatisfaction
head(newdata)

# ------------------------------------------
# 任务二
# ------------------------------------------

newdata$AverageSatisfaction <- (newdata$EnvironmentSatisfaction + newdata$JobSatisfaction + newdata$RelationshipSatisfaction) / 3
newdata$AverageSatisfaction <- newdata$TotalSatisfaction / 3


attach(newdata)
newdata$TotalSatisfaction <- EnvironmentSatisfaction + JobSatisfaction + RelationshipSatisfaction
newdata$AverageSatisfaction <- TotalSatisfaction / 3
detach(newdata)

newdata <- transform(newdata, 
                     TotalSatisfaction =  EnvironmentSatisfaction + JobSatisfaction + RelationshipSatisfaction, 
                     AverageSatisfaction = (EnvironmentSatisfaction + JobSatisfaction + RelationshipSatisfaction) / 3)

# ------------------------------------------
# 优化：round()函数 
# ------------------------------------------

a <- 1234.56789
a

round(a, 2)
round(a, 0)

newdata$AverageSatisfaction <- round(newdata$AverageSatisfaction, 0)

head(newdata)


newdata <- transform(newdata, 
                     TotalSatisfaction =  EnvironmentSatisfaction + JobSatisfaction + RelationshipSatisfaction,
                     AverageSatisfaction = round((EnvironmentSatisfaction + JobSatisfaction + RelationshipSatisfaction) / 3, 0))

head(newdata)